#include <QgsSimulation/DragTool.h>

using SimulationCore::QgsSimulation::DragTool;

DragTool::DragTool(QgsMapCanvas *mapcanvas, const QString &action)
	:QgsMapToolEmitPoint(mapcanvas),
	mapcanvas_(mapcanvas)
{
	this->crs_ = this->mapcanvas_->mapSettings().destinationCrs();
}

DragTool::~DragTool()
{
	
}

void DragTool::canvasPressEvent(QgsMapMouseEvent * e)
{
	// if left button pressed
	if (e->button() == Qt::LeftButton) {
		m_lastPanPoint = e->pos();
		m_panActive = true;
		e->accept();
	} 
	else
	{
		QgsMapToolEmitPoint::canvasPressEvent(e);
	}
}

void DragTool::canvasMoveEvent(QgsMapMouseEvent * e)
{
	if (m_panActive) {
		QPoint delta = e->pos() - m_lastPanPoint;
		pan(delta);
		m_lastPanPoint = e->pos();
		e->accept();
	} else {
		QgsMapToolEmitPoint::canvasMoveEvent(e);
	}
}

void DragTool::canvasReleaseEvent(QgsMapMouseEvent * e)
{
	if (m_panActive && e->button() == Qt::LeftButton) {
		m_panActive = false;
		e->accept();
	} else {
		QgsMapToolEmitPoint::canvasReleaseEvent(e);
	}
}

void DragTool::activate()
{
	// set cursor
	setCursor(Qt::ClosedHandCursor); 
	QgsMapToolEmitPoint::activate();
}

void DragTool::deactivate()
{
	mapcanvas_->unsetCursor();
	QgsMapToolEmitPoint::deactivate();
}

void DragTool::pan(const QPoint& delta) 
{
	// transform mouse coordinates to map coordinates
	QgsPointXY startPt = mapcanvas_->getCoordinateTransform()->toMapCoordinates(m_lastPanPoint);
	QgsPointXY endPt = mapcanvas_->getCoordinateTransform()->toMapCoordinates(m_lastPanPoint - delta);

	double dx = endPt.x() - startPt.x();
	double dy = endPt.y() - startPt.y();

	QgsRectangle extent = mapcanvas_->extent();
	extent.setXMinimum(extent.xMinimum() + dx);
	extent.setXMaximum(extent.xMaximum() + dx);
	extent.setYMinimum(extent.yMinimum() + dy);
	extent.setYMaximum(extent.yMaximum() + dy);

	mapcanvas_->setExtent(extent);
	// mapcanvas_->refresh();
}
